<!--
 * @Description: 客户列表页面 - 提供客户数据的管理和展示功能，支持路由参数动态初始化和筛选
 * @Author: lujq
 * @Date: 2025-01-13
 * @LastEditors: lujq
 * @LastEditTime: 2025-01-13 14:30:00
-->
<template>
  <div class="customer-list">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入客户名称"
            clearable
            style="width: 150px"
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="客户类型">
          <el-select
            v-model="searchForm.customerType"
            placeholder="请选择客户类型"
            clearable
            style="width: 150px"
            @change="handleSearch"
            @clear="handleSearch"
          >
            <el-option label="企业客户" value="enterprise" />
            <el-option label="个人客户" value="individual" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户等级">
          <el-select
            v-model="searchForm.level"
            placeholder="请选择客户等级"
            clearable
            style="width: 150px"
            @change="handleSearch"
            @clear="handleSearch"
          >
            <el-option label="钻石" value="diamond" />
            <el-option label="黄金" value="gold" />
            <el-option label="白银" value="silver" />
            <el-option label="青铜" value="bronze" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
            @change="handleSearch"
            @clear="handleSearch"
          >
            <el-option label="活跃" value="active" />
            <el-option label="非活跃" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"> 搜索 </el-button>
          <el-button :icon="Refresh" @click="handleReset"> 重置 </el-button>
        </el-form-item>
      </el-form>

      <div class="action-buttons">
        <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增客户 </el-button>
        <el-button
          type="danger"
          :icon="Delete"
          :disabled="!selectedRows.length"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
        <el-button :icon="Download" @click="handleExport"> 导出数据 </el-button>
      </div>
    </el-card>

    <!-- 客户列表表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="customerList"
        stripe
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="客户名称" width="120" />
        <el-table-column prop="company" label="公司名称" width="180" />
        <el-table-column prop="phone" label="联系电话" width="130">
          <template #default="{ row }">
            {{ maskPhone(row.phone) }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
        <el-table-column prop="customerType" label="客户类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.customerType === 'enterprise' ? 'primary' : 'success'" size="small">
              {{ row.customerType === 'enterprise' ? '企业' : '个人' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="客户等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelType(row.level)" size="small">
              {{ getLevelLabel(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'" size="small">
              {{ row.status === 'active' ? '活跃' : '非活跃' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalOrders" label="订单数" width="80" />
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template #default="{ row }"> {{ formatAmount(row.totalAmount) }} </template>
        </el-table-column>
        <el-table-column prop="lastOrderDate" label="最后下单" width="120">
          <template #default="{ row }">
            {{ formatDate(row.lastOrderDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="handleView(row)"> 查看 </el-button>
              <el-button type="warning" size="small" @click="handleEdit(row)"> 编辑 </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)"> 删除 </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 客户详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="客户详情"
      width="800px"
      :before-close="handleDetailClose"
    >
      <div v-if="currentCustomer" class="customer-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="客户名称">
            {{ currentCustomer.name }}
          </el-descriptions-item>
          <el-descriptions-item label="公司名称">
            {{ currentCustomer.company }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ currentCustomer.phone }}
          </el-descriptions-item>
          <el-descriptions-item label="邮箱地址">
            {{ currentCustomer.email }}
          </el-descriptions-item>
          <el-descriptions-item label="客户类型">
            <el-tag :type="currentCustomer.customerType === 'enterprise' ? 'primary' : 'success'">
              {{ currentCustomer.customerType === 'enterprise' ? '企业客户' : '个人客户' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户等级">
            <el-tag :type="getLevelType(currentCustomer.level)">
              {{ getLevelLabel(currentCustomer.level) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentCustomer.status === 'active' ? 'success' : 'info'">
              {{ currentCustomer.status === 'active' ? '活跃' : '非活跃' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总订单数">
            {{ currentCustomer.totalOrders }}
          </el-descriptions-item>
          <el-descriptions-item label="总金额">
            {{ formatAmount(currentCustomer.totalAmount) }}
          </el-descriptions-item>
          <el-descriptions-item label="最后下单">
            {{ formatDate(currentCustomer.lastOrderDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(currentCustomer.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDate(currentCustomer.updateTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="详细地址" :span="2">
            {{ currentCustomer.address }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ currentCustomer.remark || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 新增/编辑客户对话框 -->
    <el-dialog
      v-model="formVisible"
      :title="isEdit ? '编辑客户' : '新增客户'"
      width="600px"
      :before-close="handleFormClose"
    >
      <el-form ref="customerFormRef" :model="customerForm" :rules="formRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户名称" prop="name">
              <el-input v-model="customerForm.name" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司名称" prop="company">
              <el-input v-model="customerForm.company" placeholder="请输入公司名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="customerForm.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="customerForm.email" placeholder="请输入邮箱地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户类型" prop="customerType">
              <el-select v-model="customerForm.customerType" placeholder="请选择客户类型">
                <el-option label="企业客户" value="enterprise" />
                <el-option label="个人客户" value="individual" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户等级" prop="level">
              <el-select v-model="customerForm.level" placeholder="请选择客户等级">
                <el-option label="钻石" value="diamond" />
                <el-option label="黄金" value="gold" />
                <el-option label="白银" value="silver" />
                <el-option label="青铜" value="bronze" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="customerForm.address"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="customerForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleFormClose">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit"> 确定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Search, Refresh, Plus, Delete, Download } from '@element-plus/icons-vue'
import {
  getCustomerList,
  getCustomerDetail,
  createCustomer,
  updateCustomer,
  deleteCustomer,
  batchDeleteCustomers,
  exportCustomers,
} from '@/api/customer'
import {
  formatAmount,
  formatDate,
  maskPhone,
  getLevelLabel,
  isValidEmail,
  isValidPhone,
} from '@/utils'
import type { Customer } from '@/types'

// 搜索表单
const searchForm = reactive({
  name: '',
  customerType: '',
  level: '',
  status: '',
})

// 客户列表数据
const customerList = ref<Customer[]>([])
const loading = ref(false)
const selectedRows = ref<Customer[]>([])

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0,
})

// 客户详情
const detailVisible = ref(false)
const currentCustomer = ref<Customer | null>(null)

// 表单相关
const formVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const customerFormRef = ref<FormInstance>()

// 客户表单数据
const customerForm = reactive<{
  id: string
  name: string
  company: string
  phone: string
  email: string
  address: string
  province: string
  city: string
  district: string
  customerType: 'individual' | 'enterprise' | ''
  level: 'bronze' | 'silver' | 'gold' | 'diamond' | ''
  status: 'active' | 'inactive' | 'blacklist' | ''
  totalOrders: number
  totalAmount: number
  lastOrderDate: string
  remark: string
  salesManager: string
  paymentTerms: string
  lastContactDate: string
  preferredProducts: string[]
}>({
  id: '',
  name: '',
  company: '',
  phone: '',
  email: '',
  address: '',
  province: '',
  city: '',
  district: '',
  customerType: '',
  level: '',
  status: 'active',
  totalOrders: 0,
  totalAmount: 0,
  lastOrderDate: '',
  remark: '',
  salesManager: '',
  paymentTerms: '',
  lastContactDate: '',
  preferredProducts: [],
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  company: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { validator: isValidPhone, trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { validator: isValidEmail, trigger: 'blur' },
  ],
  customerType: [{ required: true, message: '请选择客户类型', trigger: 'change' }],
  level: [{ required: true, message: '请选择客户等级', trigger: 'change' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
}

// 获取等级类型
const getLevelType = (level: string) => {
  const levelMap: Record<string, string> = {
    diamond: 'danger',
    gold: 'warning',
    silver: 'info',
    bronze: 'success',
  }
  return levelMap[level] || 'info'
}

// 加载客户列表
const loadCustomerList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      // 将name字段映射为keyword参数
      ...(searchForm.name && { keyword: searchForm.name }),
      ...(searchForm.customerType && { customerType: searchForm.customerType }),
      ...(searchForm.level && { level: searchForm.level }),
      ...(searchForm.status && { status: searchForm.status }),
    }

    const { data } = await getCustomerList(params)
    if (data) {
      customerList.value = data.list || []
      pagination.total = data.total || 0
    }
  } catch (error) {
    ElMessage.error('加载客户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadCustomerList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    customerType: '',
    level: '',
    status: '',
  })
  pagination.page = 1
  loadCustomerList()
}

// 新增客户
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  formVisible.value = true
}

// 查看客户详情
const handleView = async (row: Customer) => {
  try {
    const { data } = await getCustomerDetail(row.id)
    currentCustomer.value = data
    detailVisible.value = true
  } catch (error) {
    ElMessage.error('获取客户详情失败')
  }
}

// 编辑客户
const handleEdit = async (row: Customer) => {
  try {
    const { data } = await getCustomerDetail(row.id)
    Object.assign(customerForm, data)
    isEdit.value = true
    formVisible.value = true
  } catch (error) {
    ElMessage.error('获取客户信息失败')
  }
}

// 删除客户
const handleDelete = async (row: Customer) => {
  try {
    await ElMessageBox.confirm(`确定要删除客户 "${row.name}" 吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await deleteCustomer(row.id)
    ElMessage.success('删除成功')
    loadCustomerList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个客户吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    const ids = selectedRows.value.map((row) => row.id)
    await batchDeleteCustomers(ids)
    ElMessage.success('批量删除成功')
    loadCustomerList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 导出数据
const handleExport = async () => {
  try {
    const response = await exportCustomers(searchForm)
    const customers = response.data

    // 动态导入xlsx库
    const XLSX = await import('xlsx')

    // 准备导出数据
    const exportData = customers.map((customer) => ({
      客户姓名: customer.name,
      公司名称: customer.company,
      联系电话: customer.phone,
      邮箱地址: customer.email,
      详细地址: customer.address,
      客户类型: customer.customerType === 'individual' ? '个人客户' : '企业客户',
      客户等级: customer.level,
      客户状态:
        customer.status === 'active'
          ? '活跃'
          : customer.status === 'inactive'
            ? '非活跃'
            : '黑名单',
      订单总数: customer.totalOrders,
      消费总额: customer.totalAmount,
      最后下单: customer.lastOrderDate,
      销售经理: customer.salesManager || '',
      付款条件: customer.paymentTerms || '',
      创建时间: customer.createTime,
      备注: customer.remark || '',
    }))

    // 创建工作簿
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.json_to_sheet(exportData)

    // 设置列宽
    const colWidths = [
      { wch: 12 }, // 客户姓名
      { wch: 20 }, // 公司名称
      { wch: 15 }, // 联系电话
      { wch: 25 }, // 邮箱地址
      { wch: 30 }, // 详细地址
      { wch: 10 }, // 客户类型
      { wch: 10 }, // 客户等级
      { wch: 10 }, // 客户状态
      { wch: 10 }, // 订单总数
      { wch: 12 }, // 消费总额
      { wch: 12 }, // 最后下单
      { wch: 12 }, // 销售经理
      { wch: 15 }, // 付款条件
      { wch: 20 }, // 创建时间
      { wch: 20 }, // 备注
    ]
    ws['!cols'] = colWidths

    // 添加工作表
    XLSX.utils.book_append_sheet(wb, ws, '客户数据')

    // 生成文件名
    const fileName = `客户数据导出_${new Date().toISOString().slice(0, 10)}.xlsx`

    // 导出文件
    XLSX.writeFile(wb, fileName)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 表格选择变化
const handleSelectionChange = (selection: Customer[]) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadCustomerList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadCustomerList()
}

// 提交表单
const handleSubmit = async () => {
  if (!customerFormRef.value) return

  try {
    await customerFormRef.value.validate()
    submitLoading.value = true

    // 准备提交数据，过滤空字符串
    const submitData = {
      ...customerForm,
      customerType: customerForm.customerType as 'individual' | 'enterprise',
      level: customerForm.level as 'bronze' | 'silver' | 'gold' | 'diamond',
      status: customerForm.status || ('active' as 'active' | 'inactive' | 'blacklist'),
      lastOrderDate: customerForm.lastOrderDate || new Date().toISOString(),
      salesManager: customerForm.salesManager || '',
      paymentTerms: customerForm.paymentTerms || '',
      lastContactDate: customerForm.lastContactDate || new Date().toISOString(),
      preferredProducts: customerForm.preferredProducts || [],
    }

    if (isEdit.value) {
      await updateCustomer(customerForm.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await createCustomer(submitData)
      ElMessage.success('创建成功')
    }

    formVisible.value = false
    loadCustomerList()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(customerForm, {
    id: '',
    name: '',
    company: '',
    phone: '',
    email: '',
    address: '',
    customerType: '',
    level: '',
    remark: '',
  })
  customerFormRef.value?.clearValidate()
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailVisible.value = false
  currentCustomer.value = null
}

// 关闭表单对话框
const handleFormClose = () => {
  formVisible.value = false
  resetForm()
}

// 路由实例
const route = useRoute()

/**
 * 根据路由参数初始化客户列表筛选
 * @description 支持 query: name, customerType, level, status, title
 */
const initFromRouteQuery = () => {
  const q = route.query || {}
  Object.assign(searchForm, {
    name: typeof q.name === 'string' ? q.name : '',
    customerType: typeof q.customerType === 'string' ? q.customerType : '',
    level: typeof q.level === 'string' ? q.level : '',
    status: typeof q.status === 'string' ? q.status : '',
    // 新增：支持按销售经理筛选
    salesManager: typeof q.salesManager === 'string' ? q.salesManager : '',
  })
  if (typeof q.title === 'string' && q.title) {
    document.title = `${q.title} - 布匹销售系统`
  }
}

// 首次挂载
onMounted(() => {
  initFromRouteQuery()
  loadCustomerList()
})

// 监听路由变化
watch(
  () => route.fullPath,
  () => {
    initFromRouteQuery()
    pagination.page = 1
    loadCustomerList()
  },
)
</script>

<style scoped>
.customer-list {
  padding: 0;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  white-space: nowrap;
  justify-content: flex-start;
}

.table-card {
  min-height: 600px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.customer-detail {
  padding: 16px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form .el-form-item {
    margin-bottom: 16px;
  }

  .action-buttons {
    flex-wrap: wrap;
  }

  .el-table {
    font-size: 12px;
  }
}
</style>
